﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Designer.Views
{
    public class OperationCenter
    {
        private static object s_lockObj = new object();
        private static OperationCenter s_instance;

        public static OperationCenter Instance
        {
            get
            {
                if (s_instance == null)
                {
                    lock (s_lockObj)
                    {
                        if (s_instance == null)
                        {
                            s_instance = new OperationCenter();
                        }
                    }
                }
                return s_instance;
            }
        }

        /// <summary>
        /// 执行的命令列表
        /// </summary>
        public Stack<OperationBase> DoList { get; set; }

        /// <summary>
        /// 撤销执行的命令列表
        /// </summary>
        public Stack<OperationBase> UndoList { get; set; }

        public OperationCenter()
        {
            DoList = new Stack<OperationBase>();
            UndoList = new Stack<OperationBase>();
        }

        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="operation"></param>
        public void Do(OperationBase operation)
        {
            operation.Do();
            DoList.Push(operation);
            UndoList.Clear();
        }

        /// <summary>
        /// 撤销命令执行
        /// </summary>
        public void Undo()
        {
            if (DoList.Count == 0)
            {
                return;
            }

            OperationBase operation = DoList.Pop();
            UndoList.Push(operation);
            operation.Undo();
        }

        /// <summary>
        /// 重新执行撤销的命令
        /// </summary>
        public void Redo()
        {
            if (UndoList.Count == 0)
            {
                return;
            }

            OperationBase operation = UndoList.Pop();
            DoList.Push(operation);
            operation.Do();
        }

        public void Reset()
        {
            if(s_instance != null)
            {
                s_instance.DoList.Clear();
                s_instance.UndoList.Clear();
            }
        }
    }
}
